package services

import (
	"begouser/config"
	"begouser/forms"
	"begouser/model"
	"fmt"

	"golang.org/x/crypto/bcrypt"
)

func GetUser(id int64) *model.User {
	sql := `
	select id,name,addr,sex from user4 where id =?
	`
	var (
		ids  int64
		name string
		addr string
		sex  bool
	)

	row := config.Db.QueryRow(sql, id)
	row.Scan(&ids, &name, &addr, &sex)
	return &model.User{ids, name, "", sex, addr}
}

func GetUsers() *[]model.User {
	users := make([]model.User, 0)
	sql := `
	select id,name,password,addr,sex from user4
	`
	rows, err := config.Db.Query(sql)
	if err != nil {
		fmt.Println(err)
		return nil
	}

	for rows.Next() {
		var (
			id       int64
			name     string
			password string
			addr     string
			sex      bool
		)
		rows.Scan(&id, &name, &password, &addr, &sex)
		users = append(users, *model.NewUser(id, name, password, addr, sex))
		// fmt.Println(id, name, addr, sex)
	}
	return &users
}

func AddUser(name, addr string, sex bool) {
	sql := `
	insert into user4(name,addr,sex,created_at,updated_at) values (?,?,?,now(),now());
	`
	// fmt.Println(name, addr, sex)
	result, err := config.Db.Exec(sql, name, addr, sex)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(result.RowsAffected())
}

func EditUser(id int64, name, addr string, sex bool) {
	sql := `
	update user4 set name=?,addr=?,sex=? where id=? 
	`
	_, err := config.Db.Exec(sql, name, addr, sex, id)
	if err != nil {
		fmt.Println(err)
		return
	}
	// fmt.Println(result.RowsAffected())
}

func DelUser(id int64) {
	sql := `
	delete from user4 where id = ?
	`
	result, err := config.Db.Exec(sql, id)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(result.RowsAffected())

}

func GetUserByName(name string) *model.User {
	sql := `
	select id,name,password from user4 where name=?
	`
	var (
		uid       int64
		uname     string
		upassword string
	)
	if err := config.Db.QueryRow(sql, name).Scan(&uid, &uname, &upassword); err == nil {
		return model.NewUser(uid, uname, upassword, "", false)
	}
	return nil
}

func Auth(form *forms.LoginForm) *model.User {
	if user := GetUserByName(form.Username); user == nil {
		fmt.Println(user, "aaa")
		// 用户名密码错误
		return nil
	} else {
		if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(form.Password)); err == nil {
			return user
		} else {
			// 用户名密码错误
			return nil
		}
	}

}
